﻿namespace MVVM.Services;

using System;
using System.Threading.Tasks;
using RestSharp;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

    // 定义情感分析服务类
    public class EmotionalAnalysisService 
    {
        const string API_KEY = "0wI2iE3IjBMswoVB5vwBCHcx";
        const string SECRET_KEY = "slVuyiYaDbvx1FB6JwbBy0b1j8gaaFbS";

        // 对外公开的异步分析情感的方法
        public async Task<(string Emotion, string EmotionTone, double EmotionScore)> AnalyzeEmotionAsync(string text)
        {
            if (text == "")
            {
                return ("neutral", "normal", 0.65);
            }

            var client = new RestClient($"https://aip.baidubce.com/rpc/2.0/nlp/v1/emotion?charset=UTF-8&access_token={await GetAccessToken()}");
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json");
            // var body = $"{{\"text\": \"{text}\"}}";
            var body = $@"{{""text"":""{text}""}}";
            request.AddParameter("application/json", body, ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);
                
            if (response == null || string.IsNullOrEmpty(response.Content))
            {
                throw new Exception("未能从服务器获取有效的响应内容。");
            }
            try
            {
                var result = JsonConvert.DeserializeObject<JObject>(response.Content);
                if (result == null)
                {
                    throw new Exception("未能解析响应内容。");
                }
                JToken itemsToken = result["items"]?[0];
                if (itemsToken == null)
                {
                    throw new Exception("响应中不包含情感分析结果。");
                }
                string emotion = itemsToken["label"]?.ToString();
                string emotionTone = "normal";
                double prob = itemsToken["prob"]?.Value<double>()?? 0;
                JToken subitemsToken = itemsToken["subitems"];
                if (subitemsToken!= null && subitemsToken.HasValues)
                {
                    emotionTone = subitemsToken[0]["label"]?.ToString();
                }
                double emotionScore = CalculateEmotionScore(emotion, prob);
                return (emotion, emotionTone, emotionScore);
            }
            catch (JsonException jsonEx)
            {
                throw new Exception($"解析JSON响应时发生错误：{jsonEx.Message}");
            }
            catch (Exception ex)
            {
                throw new Exception($"处理响应时发生错误：{ex.Message}");
            }

        }

        // 获取访问令牌的异步方法
        public async Task<string> GetAccessToken()
        {
            var client = new RestClient($"https://aip.baidubce.com/oauth/2.0/token");
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddParameter("grant_type", "client_credentials");
            request.AddParameter("client_id", API_KEY);
            request.AddParameter("client_secret", SECRET_KEY);
            IRestResponse response = client.Execute(request);
            var result = JsonConvert.DeserializeObject<dynamic>(response.Content);
            return result.access_token.ToString();
        }

        // 计算情感分数的方法
        static double CalculateEmotionScore(string emotion, double prob)
        {
            if (emotion == "pessimistic")
            {
                return prob * 0.35;
            }
            else if (emotion == "neutral")
            {
                return 0.35 + (0.65 - 0.35) * prob;
            }
            else if (emotion == "optimistic")
            {
                return 0.65 + prob * (1 - 0.66);
            }
            return 0;
        }
    }

